package com.example.foo.admin.web.order;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.poi.ExcelUtils;
import com.example.core.PageResult;
import com.example.core.Pageable;
import com.example.foo.order.model.Order;
import com.example.foo.order.query.OrderQuery;
import com.example.foo.order.service.OrderService;

import java.text.ParseException;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

import com.example.foo.user.model.User;
import com.example.foo.user.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;

import static com.ruoyi.common.utils.DateUtils.YYYY_MM_DD;

@org.springframework.web.bind.annotation.RestController
public class OrderAction {

    private final OrderService orderService;
    private final UserService userService;

    public OrderAction(OrderService orderService, UserService userService) {
        this.orderService = orderService;
        this.userService = userService;
    }

    @GetMapping("/api/orders")
    public AjaxResult index(OrderQuery orderQuery, Pageable pageable) {
        PageResult<Order> pageResult = orderService.findOrders(orderQuery, pageable);

        List<Order> orders = (List<Order>) pageResult.getRows();
        List<OrderVO> orderVOList = new ArrayList<>(orders.size());
        for (Order order : orders) {
            OrderVO orderVO = new OrderVO();
            User user = userService.findUserById(order.getUid());
            if (user != null){
                orderVO.setUserName(user.getName());
                orderVO.setUserHeadUrl(user.getAvatar());
            }
            BeanUtils.copyProperties(order, orderVO);
            orderVOList.add(orderVO);
        }

        return AjaxResult.successData(new PageResult<OrderVO>(orderVOList, pageResult.getTotal()));
    }

    @GetMapping("/api/orders/{id}")
    public AjaxResult showOrder(@PathVariable("id") Long id) {
        Order order = orderService.findOrderById(id);
        if (order == null) {
            return AjaxResult.error(404, "Not Found");
        }
        return AjaxResult.successData(order);
    }

    @GetMapping("/api/orders/export")
    public AjaxResult exports(OrderQuery orderQuery) throws ParseException {
        Map<String, String> map = new LinkedHashMap<>();
        map.put("订单号", "outTradeNo");
        map.put("商品标题", "goodsDetail");
        map.put("商品类型", "goodsType");
        map.put("卡号", "cardSn");
        map.put("支付时间", "payTime");
        map.put("订单金额", "totalPrice");
        map.put("实际支付金额", "payPrice");
        map.put("支付状态", "payStatusStr");
        map.put("订单状态", "orderStatus");
//        map.put("会员信息", "userInfo");
//        map.put("收货人信息", "takeUserInfo");
        map.put("收货人姓名", "realName");
        map.put("收货人电话", "userPhone");
        map.put("省份", "province");
        map.put("城市", "city");
        map.put("区县", "district");
        map.put("详细地址", "addressDetail");
        map.put("创建时间", "createdAt");

        List<Order> list = orderService.findOrderList(orderQuery);
        List<OrderVO> orderVOList = list.stream().map(this::toOrderVO).collect(Collectors.toList());
        ExcelUtils<OrderVO> excelUtils = new ExcelUtils<OrderVO>(OrderVO.class);
        return excelUtils.export(map, orderVOList, "orders.xlsx");
    }

    @PutMapping("/api/orders/{id}/delivery")
    public AjaxResult updateOrderDelivery(@PathVariable("id") Long id, Order orderForm) {
        String nowDate = DateUtils.dateTimeNow(YYYY_MM_DD);
        if (StringUtils.isBlank(orderForm.getDeliveryCompany())) {
            return AjaxResult.error(400, "物流公司不能为空");
        }
        if (StringUtils.isBlank(orderForm.getDeliverySn())) {
            return AjaxResult.error(400, "物流单号不能为空");
        }

        Order order = orderService.findOrderById(id);
        if (order == null) {
            return AjaxResult.error(404, "Not Found");
        }

        if (!Objects.equals(order.getPayStatus(), Order.PayStatus.processed.val)) {
            return AjaxResult.error(400, "该订单未支付");
        }

        order.setDeliveryCompany(orderForm.getDeliveryCompany());
        order.setDeliverySn(orderForm.getDeliverySn());
        order.setStatus(Order.Status.delivery.val);
        order.setDeliveryTime(LocalDateTime.now());
        order.setDeliveryDate(nowDate);
        orderService.updateOrder(order);

        return AjaxResult.success();
    }

    @PutMapping("/api/orders/{id}/selfWithdrawal")
    public AjaxResult selfWithdrawal(@PathVariable("id") Long id) {

        Order order = orderService.findOrderById(id);
        if (order == null) {
            return AjaxResult.error(404, "Not Found");
        }

        if (!Objects.equals(order.getPayStatus(), Order.PayStatus.processed.val)) {
            return AjaxResult.error(400, "该订单未支付");
        }

        order.setSelfWithdrawalTime(LocalDateTime.now());
        order.setStatus(Order.Status.finished.val);
        orderService.updateOrder(order);

        return AjaxResult.success();
    }

    private OrderVO toOrderVO(Order order) {
    	OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(order, orderVO);

        if(order.getStatus() == Order.Status.waitPay.val){
            orderVO.setOrderStatus("待支付");
        }else if(order.getStatus() == Order.Status.pending.val){
            orderVO.setOrderStatus("待发货");
        }else if(order.getStatus() == Order.Status.delivery.val){
            orderVO.setOrderStatus("待收货");
        }else if(order.getStatus() == Order.Status.takeDelivery.val){
            orderVO.setOrderStatus("已收货");
        }else if(order.getStatus() == Order.Status.finished.val){
            orderVO.setOrderStatus("已完成");
        }
        if(order.getPayStatus() == Order.PayStatus.pending.val){
            orderVO.setPayStatusStr("待支付");
        }else if(order.getPayStatus() == Order.PayStatus.processed.val){
            orderVO.setPayStatusStr("已支付");
        }
//        orderVO.setTakeUserInfo(order.getRealName() +"-"+order.getUserPhone());
        orderVO.setRealName(order.getRealName());
        orderVO.setUserPhone(order.getUserPhone());
        return orderVO;
    }

}
